<template>
  <common-list-group class="report-component-wrap">
    <div slot="group" class="group-list-component-wrap">
      <div class="group-header-wrap">
        <div class="group-header-title">资产类型</div>
      </div>
      <common-tree
        ref="treeRef"
        :is-slot="true"
        node-key="id"
        :isRequest="isRequest"
        :tree-data="groupTreeData"
        search-placeholder="查询分类"
        :current-node-key="currentNodeKey"
        :highlight-current="true"
        :treeLoading="treeLoading"
        :hiddenIndexIcon="3"
        @handleNodeClick="handleNodeClick"
      >
        <div slot-scope="{ scope }" class="tree-item-wrap">
          <common-carousel-text :content="scope.data.name" :font-size="14" />
          <!--
          <el-popover
            popper-class="chart-type-list-popover"
            placement="right-start"
            width="150"
            trigger="hover"
          >
            <i slot="reference" class="iconfont icon-more"></i>
            <common-menu>
              <common-menu-item @click="treeAdd(scope)"
                >新增分类</common-menu-item
              >
            </common-menu>
            <common-menu>
            <common-menu-item @click="treeEdit(scope)">重命名</common-menu-item>
            <common-menu-item @click="treeDelete(scope)">删除</common-menu-item>
            </common-menu>
          </el-popover>
          <el-popover
            v-if="scope.data.leaf"
            popper-class="chart-type-list-popover"
            placement="right-start"
            width="150"
            trigger="hover"
          >
            <i slot="reference" class="iconfont icon-more"></i>

          </el-popover> -->
        </div>
      </common-tree>
    </div>
    <!-- 头部搜素start -->

    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        v-model="query"
        ref="queryForm"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="负责人情况" prop="userCodeFlag">
          <el-select placeholder="请选择" v-model="query.userCodeFlag">
            <el-option label="全部" :value="null"> </el-option>
            <el-option label="有负责人" :value="0"> </el-option>
            <el-option label="无负责人" :value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资产编码" prop="assetCode">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="query.assetCode"
          />
        </el-form-item>
        <el-form-item label="管理地址" prop="managerIp">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="query.managerIp"
          />
        </el-form-item>

        <el-form-item label="资产类别" prop="categoryFirstCode">
          <el-select
            placeholder="请选择"
            v-model="query.categoryFirstCode"
            filterable
          >
            <el-option label="全部" :value="null"> </el-option>
            <el-option
              v-for="item in categoryFirstList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="来源" prop="sourceType">
          <el-select v-model="query.sourceType">
            <el-option label="全部" :value="null"> </el-option>
            <el-option label="手动添加" :value="0"></el-option>
            <el-option label="自动发现" :value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="网络状态" prop="status">
          <el-select v-model="query.status">
            <el-option label="全部" :value="null"> </el-option>
            <el-option label="离线" :value="'0'"></el-option>
            <el-option label="在线" :value="'1'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="业务系统" prop="businessCodeName">
          <el-select v-model="query.businessCodeName">
            <el-option label="全部" :value="null"> </el-option>
            <el-option
              v-for="item in businessCodeList"
              :key="item.dictLabel"
              :label="item.dictLabel"
              :value="item.dictLabel"
            ></el-option>
          </el-select>
        </el-form-item>

        <common-dept
          ref="commonDept"
          :currentParent="currentParent"
          @getDeptId="getDeptId"
          @getDeptList="getDeptList"
          @getLoading="getLoading"
        ></common-dept>
      </el-form>
    </common-search>

    <!-- 按钮部门start -->
    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd(null)"
          plain
          :disabled="isLoading || treeLoading"
          v-hasPermi="['analysiscenter:source:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleDelete"
          v-hasPermi="['analysiscenter:source:remove']"
          :disabled="!showBatch"
          >批量删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          @click="importShow"
          v-hasPermi="['analysiscenter:source:export']"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['analysiscenter:source:export']"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          type="primary"
          icon="el-icon-s-check"
          :disabled="!showBatch"
          @click="HandleDistributeOrg"
          v-hasPermi="['analysiscenter:source:edit']"
          >分配组织
        </el-button>
      </el-col>
    </el-row>

    <!--列表 start-->
    <common-table
      v-loading="isLoading"
      slot="content"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        fixed
        label="资产编码"
        align="left"
        prop="assetCode"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="资产名称"
        align="left"
        prop="assetName"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="资产类型" align="left" prop="name">
      </el-table-column>
      <el-table-column
        label="管理地址"
        align="left"
        prop="managerIp"
        width="160"
      >
      </el-table-column>
      <el-table-column label="负责人" align="left" prop="userCode">
      </el-table-column>
      <el-table-column
        label="组织"
        align="left"
        prop="deptName"
        width="180"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="来源" align="left" prop="sourceType" width="100">
        <template slot-scope="{ row }">
          <el-tag type="warning" v-if="row.sourceType === 0">手动添加</el-tag>
          <el-tag type="info" v-if="row.sourceType === 1">自动发现</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="网络状态" align="left" prop="status" width="80">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status === 1">在线</el-tag>
          <el-tag type="danger" v-if="row.status === 0">离线</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="采集状态"
        align="left"
        prop="logState"
        width="100"
      >
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.logState === true">已采集</el-tag>
          <el-tag type="danger" v-if="row.logState === false">未采集</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="208" fixed="right">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            @click="connectionTest(row)"
            v-hasPermi="['analysiscenter:source:connection']"
            >测试连接
          </el-button>
          <el-button type="text" @click="handleInfo(row)">资产详情</el-button>
          <el-button
            type="text"
            @click="handleEdit(row)"
            v-hasPermi="['analysiscenter:source:edit']"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(row)"
            v-hasPermi="['analysiscenter:source:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList()"
    />
    <common-upload-dialog
      download-path="system/alarm/code/downFileByemplateName"
      upload-path="/analysiscenter/source/importData"
      template-name="assetTemplate.xlsx"
      report-path="analysiscenter/source/downErrorReportByemplateName"
      ref="uploadDialog"
      :getList="getList"
    />
    <template v-if="isShowAdd">
      <add-assets
        ref="addAssets"
        @close="closeAdd"
        :departmentList="departmentList"
        :title="isTitle"
        :assetSourceEditId="assetSourceEditId"
        :terrDateName="terrDateName"
        :minMenuIds="minMenuIds"
        :businessCodeList="businessCodeList"
        @submitForm="submitFormAdd"
      ></add-assets>
    </template>
    <template v-if="isAssetDetails">
      <asset-details
        ref="assetDetails"
        @close="closeAssetDetails"
        :assetIP="assetIP"
        :assetSourceEditId="assetSourceEditId"
      ></asset-details>
    </template>
    <distribute-org
      ref="distributeOrg"
      :deptSelectArr="departmentList"
      :dialogShow="dialogShow"
      :buttonLoading="submitOrgLoading"
      @toSubmit="toDistributeOrg"
      @close="dialogShow = false"
    />
  </common-list-group>
</template>

<script>
import BaseList from "@/mixins/BaseList";
import addAssets from "./components/add";
import assetDetails from "./components/assetDetails";
import DistributeOrg from "../../apisecurity/application/components/distributeOrg.vue";

import {
  treeListAssets,
  listAssets,
  testConnection,
  delAssets,
  updateDeptId,
  queryBusinessList
} from "@/api/analysisCenter/analysis";
import { number } from "echarts";
import { getFullDept, getSingleArray } from "@/utils/util";

export default {
  name: "index",
  mixins: [BaseList],
  components: {
    addAssets,
    assetDetails,
    DistributeOrg
  },
  data() {
    return {
      submitOrgLoading: false,
      dialogShow: false,
      exportLoading: false,
      isRequest: false,
      treeLoading: false,
      treeList: [],
      assetSourceEditId: null,
      assetIP: null,
      isLoading: false,
      isAssetDetails: false,
      isTitle: false,
      ids: [],
      total: 0,
      assetId: null,
      single: true,
      multiple: true,
      list: [],
      terrDateName: "",
      query: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        userCodeFlag: null,
        managerIp: null,
        assetCode: null,
        categoryFirstCode: null,
        deptIds: null,
        sourceType: null,
        status: null,
        businessCodeName: null
      },
      groupTreeData: [],
      groupTreeProp: {},
      currentNodeKey: "0",
      treeIds: [],
      getParentNodeData: [],
      isShowAdd: false,
      categoryFirstList: [],
      currentParent: 1,
      departmentList: [],
      minMenuIds: [],
      businessCodeList: []
    };
  },
  methods: {
    getLoading() {
      this.loading = true;
    },
    getCheckedDeptId(val) {
      // this.typeForm.deptId = val;
    },
    getDeptList(list) {
      this.departmentList = list;
      this.singleDeptList = getSingleArray(list);
      this.getList();
    },
    getDeptId(val) {
      this.query.deptIds = val;
    },
    getDeptName(val) {
      let dept = this.singleDeptList.find(item => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },
    handleNodeClick(data) {
      this.isRequest = true;
      this.query.pageNum = 1;
      this.query.pageSize = 10;
      data.node.level === 1
        ? (this.query.parentId = null)
        : (this.query.parentId = data.data.id);
      this.getList();
      if (data.node.level !== 1) {
        this.terrDateName = data.data.id;
      } else {
        this.terrDateName = "";
      }
      if (data.data.leaf) {
        this.minMenuIds = [
          data.node.parent.parent.data.id,
          data.data.parentId,
          data.data.id
        ];
      } else {
        this.minMenuIds = [];
      }
    },
    // treeAdd(row) {
    //   //树节点新增
    //   console.log(row);
    // },
    // treeEdit(row) {
    //   //树节点重命名
    //   console.log(row);
    // },
    // treeDelete(row) {
    //   // 树节点删除
    //   console.log(row);
    // },

    treeGetList() {
      this.treeLoading = true;
      // 树节点列表
      treeListAssets()
        .then(res => {
          if (res && res.code === 200) {
            this.categoryFirstList = [];
            res.data.forEach(item => {
              this.categoryFirstList.push({
                label: item.name,
                value: item.id
              });
            });
            this.groupTreeData = [
              {
                name: "资产类别",
                id: "0",
                children: res.data
              }
            ];
          } else {
            this.groupTreeData = [];
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.treeLoading = false;
        });
    },

    getList() {
      // 列表

      this.isLoading = true;
      listAssets(this.query)
        .then(res => {
          if (res && res.code === 200) {
            this.list = res.rows;
            this.list.forEach(item => {
              item.deptName = this.getDeptName(item.deptId || "");
            });
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.isLoading = false;
          this.isRequest = false;
        });
    },
    HandleDistributeOrg() {
      this.dialogShow = true;
      this.$refs.distributeOrg.show();
    },

    toDistributeOrg(val) {
      if (val) {
        this.submitOrgLoading = true;
        updateDeptId({ sourceIds: this.ids.join(), deptId: val })
          .then(res => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("分配成功");
              this.dialogShow = false;
              this.getList();
            } else {
              this.$GlobalErrorConfirm("分配失败", res.msg);
            }
          })
          .catch(err => {
            this.$GlobalErrorConfirm("分配失败", err.msg);
          })
          .finally(() => {
            this.submitOrgLoading = false;
          });
      } else {
        this.$GlobalErrorConfirm("分配失败", "请选择组织");
      }
    },

    handleAdd() {
      //新增按钮

      this.isTitle = false;
      this.isShowAdd = true;
    },
    handleEdit(row) {
      // 编辑
      this.assetSourceEditId = row.assetSourceId;
      this.isTitle = true;
      this.isShowAdd = true;
    },
    //多选
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.assetSourceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleDelete(row) {
      // 删除
      const ids = row.assetSourceId || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          delAssets({ ids }).then(res => {
            if (res && res.code == 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.query.pageNum > 1 &&
                ids.split(",").length === this.list.length
              ) {
                this.query.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg).then();
            }
          });
        })
        .catch(() => {});
    },
    handleInfo(row) {
      // 详情
      // console.log(row);
      this.assetSourceEditId = row.assetSourceId;
      this.assetIP = row.managerIp;
      this.isAssetDetails = true;
    },
    //连接测试
    connectionTest(row) {
      this.$GlobalDeleteConfirm("确定要进行测试连接么?")
        .then(() => {
          testConnection({
            assetSourceId: row.assetSourceId,
            managerIp: row.managerIp
          }).then(res => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage(res.msg);
              this.getList();
            } else {
              this.$GlobalErrorConfirm("测试连接失败", res.msg).then(() => {
                this.getList();
              });
            }
          });
        })
        .catch(() => {});
    },
    closeAdd() {
      this.isShowAdd = false;
    },
    submitFormAdd() {
      this.isShowAdd = false;
      this.getList();
    },
    closeAssetDetails() {
      this.isAssetDetails = false;
    },
    importShow() {
      //导入
      this.$refs.uploadDialog.show();
    },
    handleExport() {
      //导出
      this.exportLoading = true;
      this.download(
        "analysiscenter/source/export",
        {
          ...this.query,
          pageSize: 10000
        },
        `assetTemplate_${new Date().getTime()}.xlsx`
      ).finally(() => {
        this.exportLoading = false;
      });
    },
    handleQuery() {
      //查询
      this.query.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      // 重置
      this.query = this.$options.data().query;
      this.$refs.commonDept.clearDept();
    },
    queryBusinessCodeList() {
      queryBusinessList().then(res => {
        if (res && res.code === 200) {
          this.businessCodeList = res.data;
        } else {
          this.businessCodeList = [];
        }
      });
    }
  },

  mounted() {
    this.treeGetList();
    this.queryBusinessCodeList();
  }
};
</script>

<style scoped lang="scss">
.report-component-wrap {
  .tree-item-wrap {
    display: flex;
    align-items: center;
    width: 100%;

    .tree-label {
      margin-right: 4px;
    }

    .pre-icon {
      width: 12px;
      height: 12px;
      font-size: 12px;
    }
  }

  .group-header-wrap {
    height: 32px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-header-title {
      font-size: 14px;
    }
  }
}
::v-deep .el-table .el-tag--info.el-tag {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #d9ecff;
}
</style>
